<template>
  <div>
    <div class="pageheader">
      <XHeader :left-options="{backText:''}" :title="xheader.title" class="XHeader"></XHeader>
    </div>
    <div class="pagetop">
      <div class="toptab">
        <div
          v-for="(item,index) in tab"
          :key="index"
          class="item"
          :class="tabIndex==index?'active':''"
          @click="onTabTap(index)"
        >{{item.text}}
        </div>
      </div>
    </div>
    <scroller
      @on-pullup-loading="getOrderList"
      lock-x
      ref="scroller"
      :pullup-config="{content:'',upContent:'',downContent:'释放加载更多',loadingContent:'加载中...',}"
      height="-45"
      :use-pullup="true"
      v-model="status"
    >
      <div class="page">
        <div class="order-main" v-for="(item,index) in orderList" :key="index">
          <div class="brokerageitem">
            <div class="brokerageitem-goods">
              <div class="order-con">
                <div class="header" @click="onInfo(item, goodItem)">
                  <div class="header-con">
                    <div>订单号: {{item.order_info.order_sn}}</div>
                    <div>{{item.order_info.date_create}}</div>
                  </div>
                  <div class="header-con">
                    <div>
                      <div class="ordernumber order-num" v-if="isJinDong(item.seller_member_id)">
                        {{textOrderNum(item.seller_member_id)}}:{{goodItem.sub_order_sn}}
                      </div>
                      <div class="ordernumber order-num" v-else-if="isSuNing(item.seller_member_id)">
                        {{textOrderNum(item.seller_member_id)}}:{{goodItem.sub_order_sn}}
                      </div>
                    </div>
                    <div class="state">{{item.order_info.order_state_desc}}</div>
                  </div>
                </div>

                <div class="content" v-for="(goodItem,goodIndex) in item.order_goods" :key="goodIndex" @click="onMallInfo(goodItem)">
                  <div class="content-box">
                    <chimage class="image" :src="goodItem.goods_sku_image"></chimage>
                    <div class="content-box-goods">
                      <div class="titlebar">
                        <div class="title">{{goodItem.goods_name}}</div>
                        <div class="price">
                          <div class="price-text">￥{{goodItem.goods_price}}</div>
                          <div class="tip">x{{goodItem.goods_sku_number}}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="pricebar tip" @click.stop>
                    <span>小计: </span>
                    <span class="price-text">￥{{(goodItem.goods_sku_number * goodItem.goods_price).toFixed(2)}}</span>
                  </div>

                  <div class="pricebar pricebar-btn" @click.stop style="margin: 0">
                    <div
                      v-if="parseFloat(goodItem.apply_after_sale) !== 1 && item.order_state == 40"
                      class="buttom"
                      @click="onAfter(item, goodItem)"
                    >售后
                    </div>

                    <template v-if="ifEvaluate(item, goodItem.is_comment)">
                      <div
                        v-if="goodItem.after_sale!='0' && item.order_state == 40"
                        class="buttom"
                        @click="onEvaluation(goodItem)"
                      >立即评价
                      </div>
                    </template>
                    <template v-else>
                      <div
                        v-if="20 <= item.order_state && (isSuNing(item.seller_member_id))"
                        class="buttom buttomred"
                        @click="onLogistics(item, goodItem, goodItem)"
                      >查看物流
                      </div>
                    </template>
                  </div>
                </div>
              </div>

              <div class="footer">
                <div class="left">
                  <div>支付方式: 微信支付</div>
                  <div class="left-item">
                    <span>订单总额:</span>
                    <span class="price-text">￥{{ (item.order_info.order_amount_goods + item.order_info.order_amount_freight).toFixed(2) }}</span>
                    <span class="tip" style="margin: 0">{{parseFloat(item.order_info.order_amount_freight) ? '（含运费￥' + item.order_info.order_amount_freight.toFixed(2) + ')':'(免运费)'}}</span>
                  </div>
                </div>
                <div class="right">
                  <div
                    v-if="item.order_state==ordersState['待收货']"
                    class="buttom buttomred"
                    @click="onConfirm(item)"
                  >确认收货
                  </div>
                  <div v-if="item.order_info.allow_cancal" class="buttom" @click="onCancel(item)">取消订单</div>
                  <div v-if="item.order_info.allow_delete" class="buttom" @click="onDelete(item.order_info.order_sn)">删除</div>
                  <div
                    v-if="parseFloat(item.sure_make_invoice) === 1 && !isXBZG"
                    class="buttom"
                    @click="onInvoice(item, goodItem)"
                  >查看发票
                  </div>
                  <div
                    v-if="20 <= item.order_state && (isJinDong(item.seller_member_id))"
                    class="buttom buttomred"
                    @click="onLogistics(item, goodItem, null)"
                  >查看物流
                  </div>
                  <div v-if="item.order_info.order_state==ordersState['待付款']" class="buttom buttomred" @click="onPay(item)"
                  >立即支付
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <load-more
          v-if="!more&&!orders.length"
          :show-loading="false"
          :tip="'暂无数据'"
          background-color="#fbf9fe"
        ></load-more>
      </div>
    </scroller>
    <popup v-model="isConfirm">
      <checklist title="请选择" label-position="left" :options="confirmList" v-model="confirmValue"></checklist>
      <div style="margin:15px 0">
        <button class="button" @click="onConfirmTap">确认收货</button>
      </div>
    </popup>

    <!--自营查看物流弹框-->
    <actionsheet
      v-model="isLogisticsZy"
      :menus="logisticsZyList"
      :value="false"
      name="name"
      :close-on-clicking-mask="true"
      @on-click-menu="onLogisticsZyMenus"
    >
    </actionsheet>
  </div>
</template>

<script>
  import Enum from '@/config/enum'
  import Me from '@/dll/me'
  // import Pay from '@/dll/pay'
  // import util from '@/utils/util'
  import Order from '../../../../mixin/order'

  export default {
    name: 'mallOrder',
    mixins: [Order],
    data () {
      let tab = []
      for (var i in Enum.IN_PURCHASING_ORDERS_STATE) {
        tab.push({
          text: i,
          state: Enum.IN_PURCHASING_ORDERS_STATE[i]
        })
      }
      return {
        xheader: {
          title: '内购订单'
        },
        // 标签页
        tab: tab,
        // 选中标签
        tabIndex: 0,
        // 订单列表
        orderList: [],
        page: 1,
        more: true,
        isConfirm: false,
        confirmList: [],
        confirmValue: [],
        wxPayUrl: '',
        ordersState: Enum.MALL_ORDERS_STATE,
        status: {
          pullupStatus: 'default'
        },

        // 自营查看物流
        isLogisticsZy: false,
        logisticsZyList: []
      }
    },
    created () {
    },
    activated () {
      this.init()
    },
    computed: {
      ifEvaluate () {
        return (item, comment) => {
          let index = this.tabIndex
          let tabItem = this.tab[index]
          return (item.order_state === Enum.IN_PURCHASING_ORDERS_STATE.已完成 && comment == 0 && tabItem.state === Enum.IN_PURCHASING_ORDERS_STATE.待评价)
        }
      },

      // 判断是否含有运费
      isShippingFee () {
        return (fee) => {
          let _fee = parseFloat(fee.sub_order_freight)
          let _feeQuota = parseFloat(fee.sub_shipping_quota)
          if (_fee === 0 || _fee === 0.00) {
            return '( 免运费 )'
          } else {
            if (_feeQuota === 0 || _feeQuota === 0.00) {
              return `( 含总运费￥${_fee.toFixed(2)} )`
            } else {
              return `<div>( 含总运费￥${_fee.toFixed(2)}，额度抵扣￥${_feeQuota ? _feeQuota.toFixed(2) : '0.00'} )<div></div>`
            }
          }
        }
      }
    },
    methods: {
      onSearchTap () {
      },
      async onConfirm (item) {
        let confirmList = []
        if (this.isZY(item.seller_member_id)) {
          for (let i in item.delivery_info) {
            if (item.delivery_info[i].state == 1) {
              confirmList.push({
                value:
                  item.delivery_info[i].express +
                  ' ' +
                  item.delivery_info[i].code,
                key: item.delivery_info[i].e_id
              })
            }
          }
        } else if (this.isYX(item.seller_member_id)) {
          for (let i in item.children_order) {
            if (parseFloat(item.children_order[i].packageStatus) === 1) {
              confirmList.push({
                value: item.children_order[i].packageId,
                key: item.children_order[i].packageId
              })
            }
          }
        } else if (this.isJinDong(item.seller_member_id) || this.isSuNing(item.seller_member_id)) {
          this.$vux.confirm.show({
            title: '提示',
            content: '是否确认收货',
            showCancelButton: true,
            onConfirm: async () => {
              let params
              let server
              if (this.isJinDong(item.seller_member_id)) {
                server = Me.confirmJdOrder
                params = { order_sn: item.order_sn, jd_order_id: item.goods_list[0].sub_order_sn }
              }
              if (this.isSuNing(item.seller_member_id)) {
                server = Me.confirmSnOrder
                params = { order_sn: item.order_sn, suning_order_sn: item.goods_list[0].sub_order_sn }
              }
              this.$vux.loading.show({
                text: '请稍后'
              })
              let res = await server(params)
              this.$vux.loading.hide()
              if (res.code == 0) {
                this.$vux.alert.show({
                  title: '提示',
                  content: '已确认收货',
                  onHide: () => {
                    this.init()
                  }
                })
              } else {
                this.$vux.alert.show({
                  title: '提示',
                  content: res.msg
                })
              }
            }
          })
        }

        if (confirmList.length) {
          this.isConfirm = true
          this.confirmList = confirmList
          this.confirmItem = item
        }
      },
      onConfirmTap () {
        if (!this.confirmValue.length) {
          this.$vux.alert.show({
            title: '提示',
            content: '请选择物流信息'
          })
        } else {
          this.isConfirm = false
          this.confirm()
        }
      },
      async confirm () {
        let confirmExpFun
        let param = {}
        let item = this.confirmItem
        let confirmValue = this.confirmValue
        let tempid = []
        for (let i in confirmValue) {
          tempid.push(confirmValue[i])
        }
        if (item.seller_member_id > 0) {
          param.order_id = item.purchase_order_id
          param.express_id = tempid.join(',')
          confirmExpFun = Me.mallZyOrderConfirmExp
        } else if (item.seller_member_id == -2) {
          param.order_id = item.children_order.orderId
          param.package_id = tempid.join(',')
          confirmExpFun = Me.mallYxOrderConfirmExp
        }
        if (confirmExpFun) {
          this.$vux.loading.show({
            text: '加载中'
          })
          let res = await confirmExpFun(param)
          this.$vux.loading.hide()
          if (res.code == 0) {
            this.$vux.alert.show({
              title: '提示',
              content: '已确认收货',
              onHide: () => {
                this.init()
              }
            })
          } else {
            this.$vux.alert.show({
              title: '提示',
              content: res.msg
            })
          }
        }
      },
      onAfter (item, goodItem) {
        if (!goodItem) {
          this.$router.push({
            name: 'mallOrderAfterSaleApply',
            query: { goodItem: JSON.stringify(item), item: JSON.stringify(item) }
          })
          return
        }
        this.$router.push({
          name: 'mallOrderAfterSaleApply',
          query: { goodItem: JSON.stringify(goodItem), item: JSON.stringify(item) }
        })
      },
      onMallInfo (goodsItem) {
        this.$router.push({
          name: 'mallInfo',
          params: { goodsId: goodsItem.goods_id }
        })
      },
      onInfo (item, goodItem) {
        let type
        if (this.isJinDong(item.seller_member_id)) {
          type = 2 // 京东
        } else if (this.isSuNing(item.seller_member_id)) {
          type = 4 // 苏宁
        } else if (this.isYX(item.seller_member_id)) {
          type = 2 // 严选
        } else if (this.isZY(item.seller_member_id)) {
          type = 1 // 自营
        }

        this.$router.push({
          name: 'mallOrderInfo',
          params: { id: item.order_sn },
          query: { type: type, subOrderId: goodItem.sub_order_sn, item }
        })
      },
      init () {
        this.page = 1
        this.more = true
        this.orderList = []
        this.getOrderList()
      },
      onTabTap (index) {
        if (this.tab[index].state == '售后') {
          this.$router.push({ name: 'mallOrderAfferSale' })
          return
        }
        this.tabIndex = index
        this.status.pullupStatus = 'disabled'
        this.$nextTick(function () {
          this.$refs.scroller.enablePullup()
          this.$refs.scroller.reset({
            top: 0
          })
          this.status.pullupStatus = 'default'
        })
        this.init()
      },

      // 立即评价
      onEvaluation (item) {
        this.$router.push({
          name: 'mallOrderComment',
          query: { order_id: item.purchase_order_id, goods_sku: item.goods_sku, goods_image: item.goods_image }
        })
      },

      // 获取订单列表
      async getOrderList () {
        let tab = this.tab
        let index = this.tabIndex
        let tabItem = tab[index]
        let page = this.page
        let res = null
        let param = {
          page: page
        }
        if (!this.more) {
          return
        }
        this.$vux.loading.show({ text: '数据加载中...' })
        if (tabItem.state != Enum.IN_PURCHASING_ORDERS_STATE.所有订单) {
          param.order_state = tabItem.state
        }
        res = await Me.getOrderList(param)
        this.$vux.loading.hide()
        if (res.code == 0) {
          if (page >= res.data.page_info.page_total) {
            this.more = false
            this.$refs.scroller.disablePullup()
          } else {
            this.$refs.scroller.donePullup()
          }

          this.page = page + 1
          this.orderList = [].concat(this.orderList, res.data.list)
          this.$forceUpdate()
        } else {
          this.more = false
          this.$forceUpdate()
          this.$refs.scroller.disablePullup()
          // this.$vux.alert.show({
          //   title: "提示",
          //   content: res.msg,
          // });
        }
      },

      // 查看物流
      onLogistics (item, goodItem, childItem) {
        let orderId
        let type
        if (this.isJinDong(item.seller_member_id)) {
          orderId = goodItem.sub_order_sn
          type = item.seller_member_id === -1 ? 1 : 2
        }
        if (this.isSuNing(item.seller_member_id)) {
          orderId = childItem.order_item_id
          type = 3
        }
        this.$router.push({
          name: 'logistics',
          query: { orderId: orderId, type: type }
        })
      },

      async confirmReceive (order_sn, jd_order_id) {
        this.$vux.loading.show({
          text: '请稍后'
        })
        let params = { order_sn, jd_order_id }
        let res = await Me.confirmJdOrder(params)
        this.$vux.loading.hide()
        if (res.code == 0) {
          this.$vux.alert.show({
            title: '提示',
            content: '已确认收货',
            onHide: () => {
              this.init()
            }
          })
        } else {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg
          })
        }
      },

      // 删除已取消订单
      async onDelete (order_sn) {
        this.$vux.confirm.show({
          title: '提示',
          content: '是否删除该订单?',
          showCancelButton: true,
          onConfirm: async () => {
            this.$vux.loading.show({ text: '数据加载中...' })
            let res = await Me.OrderDelete({ order_sn: order_sn })
            this.$vux.loading.hide()
            if (res.code == 0) {
              this.$vux.alert.show({
                title: '提示',
                content: '删除成功',
                onHide: () => {
                  this.init()
                }
              })
            } else {
              this.$vux.alert.show({
                title: '提示',
                content: res.msg
              })
            }
          }
        })
      },

      onInvoice (item, goodItem) {
        let invoiceDetail = {
          sub_order_id: goodItem.sub_order_sn,
          order_sn: item.order_sn,
          order_state: item.order_state,
          state_desc: item.order_state_desc,
          created_date: item.created_time
        }
        this.$router.push({ name: 'invoiceDetail', query: { invoiceDetail: JSON.stringify(invoiceDetail) } })
      },

      // 自营查看物流
      onLogisticsZy (item) {
        let confirmList = []
        if (item.delivery_info && item.delivery_info.length) {
          if (item.delivery_info.length === 1) {
            let params = {
              express_no: item.delivery_info[0].code,
              order_id: item.delivery_info[0].purchase_order_id,
              express_com: item.delivery_info[0].express,
              sellerMemberId: item.seller_member_id
            }

            this.onLogisticsZyMenus(params)
          } else {
            for (let i in item.delivery_info) {
              confirmList.push({
                value: {
                  express_no: item.delivery_info[i].code,
                  order_id: item.delivery_info[i].purchase_order_id,
                  express_com: item.delivery_info[i].express,
                  sellerMemberId: item.seller_member_id
                },
                label: item.delivery_info[i].express
              })
            }
          }
        }

        if (confirmList.length) {
          this.isLogisticsZy = true
          this.logisticsZyList = confirmList
        }
      },

      // 点击弹框查看物流按钮
      onLogisticsZyMenus (params) {
        this.$router.push({
          name: 'logistics',
          query: { paramsZY: params }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .page {
    padding-top: 45px;
    padding-bottom: 12px;
  }

  .pagetop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
  }

  .toptab {
    box-sizing: border-box;
    width: 100%;
    display: flex;
    padding-left: 12px;
    padding-right: 12px;
    height: 45px;
    background-color: #fff;
  }

  .toptab > .item {
    flex: 1;
    height: 100%;
    display: block;
    line-height: 45px;
    font-size: 14px;
    color: #351009;
    opacity: 0.2;
    text-align: center;
    position: relative;
  }

  .toptab > .item.active {
    opacity: 1;
    color: #2196F3;
  }

  .toptab > .item.active::after {
    position: absolute;
    content: "";
    width: 100%;
    bottom: 0;
    left: 0;
    height: 1px;
    background: #2196F3;
  }

  .brokerageitem .footer .group {
    height: 24px;
    display: block;
    box-sizing: border-box;
    width: 54px;
    border: 1px solid #46241e;
    font-size: 10px;
    color: #46241e;
    line-height: 22px;
    text-align: center;
    border-radius: 12px;
  }

  .brokerageitem .footer .group.grouping {
    color: #FF5722;
    border-color: #FF5722;
  }

  .brokerageitem .footer .group + .group {
    margin-left: 8px;
  }

  /*新订单列表样式*/
  .order-main {
    margin-top: 10px;
    padding: 0 10px;
  }

  .brokerageitem {
    border-radius: 10px;
    background-color: #fff;

    .brokerageitem-goods {
      border-bottom: 2px solid #f2f2f2;

      &:last-child {
        border: none;
      }
    }

    .order-con {
      width: 100%;
    }

    .tip {
      color: #808080;
      margin-left: 9px;
    }

    .price-text {
      color: #FF5722;
      font-size: 14px;
    }

    .header {
      color: #808080;
      font-size: 12px;
      padding: 10px 10px 5px;

      .header-con {
        display: flex;
        justify-content: space-between;

        &:first-child {
          margin-bottom: 10px;
          padding-bottom: 10px;
          border-bottom: 1px solid rgba(242, 242, 242, 1);
        }

        .state {
          width: 58px;
          height: 24px;
          color: #fff;
          font-size: 12px;
          background: rgba(255, 87, 34, 1);
          border-radius: 10px 0px 0px 10px;
          line-height: 24px;
          text-align: center;
        }
      }
    }

    .content {
      padding: 10px;

      .content-box {
        display: flex;

        .content-box-goods {
          flex: 1;
        }
      }

      .image {
        width: 70px;
        height: 70px;
        flex-shrink: 0;
        margin-right: 10px;
        background: rgba(243, 243, 243, 1);
      }

      .titlebar {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 70px;
      }

      .title {
        color: #333333;
        font-size: 14px;
        height: 38px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        font-weight: normal;
      }

      .price {
        display: flex;
        font-size: 12px;
        height: 32px;
        align-items: flex-end;
      }

      .pricebar {
        font-size: 12px;
        text-align: right;
      }

      .pricebar + .pricebar {
        margin-top: 10px;
      }
    }

    .pricebar-btn {
      display: flex;
      justify-content: flex-end;
    }

    .buttom {
      width: 72px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      border: 0.5px solid #b2b2b2;
      border-radius: 24px;
      color: #353535;
      font-size: 12px;
      margin-top: 10px;
    }

    .buttomred {
      color: #fff;
      border-color: #E3211E;
      background-color: #E3211E;
    }

    .buttom + .buttom {
      margin-left: 8px;
    }

    .footer {
      padding: 0 15px 10px;
      font-size: 12px;
      color: #333333;
      text-align: right;

      .left {
        border-top: 1px solid rgba(242, 242, 242, 1);
        padding-top: 15px;

        .left-item {
          margin-top: 8px;
        }
      }

      .right {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
  }

</style>
